package com.ruoyi.diagnosis.util;



import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortInvalidPortException;
import lombok.extern.slf4j.Slf4j;

import java.util.TooManyListenersException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * @Projectname: ModeBusPortCommunication
 * @Filename: ModBusCommandUtil
 * @Author: FANSEA
 * @Data:2024/7/8 14:56
 */
@Slf4j
public class ModBusCommandUtil {


    /**
     * 打开电脑上指定的串口
     *
     * @param portName 端口名称，如 COM1，为 null 时，默认使用电脑中能用的端口中的第一个
     * @param baudRate        波特率(baudrate)，如 9600
     * @param dataBits        数据位（datebits），如 SerialPort.DATABITS_8 = 8
     * @param stopBits        停止位（stopbits），如 SerialPort.STOPBITS_1 = 1
     * @param parity          校验位 (parity)，如 SerialPort.PARITY_NONE = 0
     * @return 打开的串口对象，打开失败时，返回 null
     */
    public static SerialPort openPort(String portName,Integer baudRate, Integer dataBits, Integer stopBits, Integer parity) {
        log.info("开始打开串口: portName = " + portName + ",baudrate = " + baudRate + ",datebits = " + dataBits + ",stopbits = " + stopBits + ",parity = " + parity);
        SerialPort serialPort = SerialPort.getCommPort(portName);
        try {
            if (!serialPort.openPort()){
                log.info("串口打开失败: portName = " + portName);
                return null;
            }
        } catch (SerialPortInvalidPortException e){
            log.error("串口打开失败，请检查端口名称是否正确: portName = " + portName, e);
            return null;
        }
        log.info("已开启串口: portName = " + portName);
        serialPort.setComPortParameters(baudRate, dataBits, stopBits, parity);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
        return serialPort;
    }



    public static void handleModbusCommand(byte[] command) {
        // 在这里处理Modbus命令
        System.out.println("Received command: " + bytesToHex(command));
        // 实现你的处理逻辑
        // 1.校验CRC码确定是否为合法指令
        // 2.如果是数据上报指令，截取起止寄存器地址，执行数据读取操作
    }

    public static void sendModbusCommand(byte[] command) {
        // 在这里发送Modbus命令
        System.out.println("Sending command: " + bytesToHex(command));
        // 实现你的发送逻辑
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

    public static void closePort(SerialPort serialPort) {
        serialPort.closePort();
    }

    /**
     * 给串口设置监听
     */
    public static void setListenerToSerialPort(SerialPort serialPort, SerialPortDataListener listener) throws TooManyListenersException {
        //serialPort.removeEventListener();
        //给串口添加事件监听
        serialPort.addDataListener(listener);
    }
}